const express = require('express')
const router = express.Router()
const userModel=require('../db/model/userModel')
const mailHelper=require('../helpers/mailHelper')

let codes={} //内存中存放验证码

/**
 * @api {post} /user/reg 用户注册
 * @apiName /user/reg
 * @apiGroup User
 *
 * @apiParam {String} username 用户名.
 * @apiParam {String} password 用户密码.
 * @apiParam {String} code 验证码.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.post('/reg',(req,res)=>{
    let {us,ps,code}=req.body
    if(!us||!ps||!code) return res.send({err:-1,msg:'参数错误'})

    if(code!=codes[us]) return res.send({err:-4,msg:'验证码不正确'})

    userModel.find({us})
    .then((data)=>{
        if(data.length===0){
            // 用户名不存在 可以注册
            return userModel.insertMany({us,ps})

        }else{
            res.send({err:-3,msg:'用户名已存在'})

        }
    })
    .then(()=>{
        res.send({err:1,msg:'注册成功'})
    })
    .catch((err)=>{
        res.send({err:-2,msg:'注册错误'})
    })  
})


router.post('/login',(req,res)=>{
    let {us,ps}=req.body
    if(!us||!ps) return res.send({err:-1,msg:'参数错误'})

    userModel.find({us,ps})
    .then((data)=>{
        console.log(data);  
        if(data.length>0){
            res.send({err:1,msg:'登录成功'})
        }else{
            res.send({err:-2,msg:'用户名或密码错误'})
        }          
    })
    .catch((err)=>{
        res.send({err:-1,msg:'内部错误'})
    })  
})


router.post('/getMailCode',(req,res)=>{
    let {mail}=req.body
    let code=parseInt(Math.random()*10000)
    mailHelper.send(mail,code)
    .then((data)=>{
        codes[mail]=code
        res.send({err:1,msg:'验证码发送成功'})
    })
    .catch((err)=>{
        res.send({err:-1,msg:'验证码发送失败'})
    })

    
})

module.exports=router
